package org.goldenport.g3.pipes

import java.net.URI
import java.io.File
import org.goldenport.g3._
import org.goldenport.g3.adapters.FileDriver
import org.goldenport.g3.adapters.HttpDriver

/**
 * @since   Sep. 18, 2010
 * @version Sep. 26, 2010
 * @author  ASAMI, Tomoharu
 */
class G3Put(val uri: String, context: G3Context) extends G3Pipe(context) with ActivityActionable {
  lazy val gDataSource = context.getDataSource(uri)
  lazy val fileDriver = new FileDriver(uri)
  lazy val httpDriver = new HttpDriver(gDataSource.uri)

  def create_Activity(ctx: G3AgentContext) = new PartialFunction[AnyRef, AnyRef] {
    def isDefinedAt(in: AnyRef) = {
      def is_file_content = {
        gDataSource.getFile.isDefined &&
        file_activity(ctx).isDefinedAt(in)
      }

      def is_http_content = {
        (gDataSource.uri.getScheme match {
          case "http" => true
          case "https" => true
          case _ => false
        }) &&
        http_activity(ctx).isDefinedAt(in)
      }

      is_file_content || is_http_content
    }

    def apply(in: AnyRef) = {
      gDataSource.getFile match {
        case Some(file) => file_activity(ctx)(in)
        case None => http_activity(ctx)(in)
      }
    }
  }

  private def file_activity(ctx: G3AgentContext) = {
    fileDriver.createDriverActivity(ctx)
  }

  private def http_activity(ctx: G3AgentContext) = {
    httpDriver.createDriverActivity(ctx)
  }
}
